<?php

namespace StudyBuddy\Api;

use StudyBuddy\FS\Path;

/**
 * Class for parsing uploaded image
 * to be used as APP icon.
 * This image is uploaded from the
 * "Add/Edit your Application" url
 * 
 */
class IconParser {

    /**
     * Parse the avatar file in $tempPath,
     * by creating small square image from it,
     * save into file system and then add path to new avatar
     * in User object as 'avatar' element
     *
     *
     * @param User $oUser
     * @param unknown_type $tempPath
     * @throws \StudyBuddy\Exception
     *
     * @return bool false if unable to parse image | true if added image 
     */
    public static function addIcon(Clientdata $o, $tempPath) {

        d('$tempPath: ' . $tempPath);

        $size = 72;

        $avatarDir = STUDYBUDDY_DATA_DIR . 'img' . DIRECTORY_SEPARATOR . 'avatar' . DIRECTORY_SEPARATOR . 'sqr' . DIRECTORY_SEPARATOR;
        d('$avatarDir: ' . $avatarDir);

        $savePath = Path::prepare($o['_id'], $avatarDir);
        d('$savePath: ' . $savePath);

        /**
         * Create avatar and save it
         * with compression level of 80% (small compression)
         */
        try {
            $ImgParser = \StudyBuddy\Image\Editor::factory($o->getRegistry())
                    ->loadImage($tempPath)
                    ->makeSquare($size);
            $savePath .= $ImgParser->getExtension();
            $ImgParser->save($avatarDir . $savePath, null, 80);
            d('avatar saved to ' . $savePath);
        } catch (\StudyBuddy\ImageException $e) {
            e('ImageException caught in: ' . $e->getFile() . ' on line: ' . $e->getLine() . ' error: ' . $e->getMessage());

            return false;
        }

        /**
         * Now remove tempPath file
         */
        @\unlink($tempPath);

        /**
         * Now add the path to avatar
         * to Clientdata object
         * save() is not invoked on Clientdata object here!
         * Either rely on auto-save  or call save()
         * from a function that invoked this method
         */
        $o['icon'] = $savePath;

        return true;
    }

}
